<?php
/* 
 * 指标附件操作
 * 主要用于神秘人上传相应的证据附件,
 */
class AttachController extends AdminController{
    /**
     * 某个客户下某个问卷的某一个问题的附件列表
     */
    public function actionList(){
        $answer_id = $this->get('answer_id');
        $criteria = new CDbCriteria();
        $criteria->addColumnCondition(array('answer_id' => intval($answer_id)));
        $criteria->addColumnCondition(array('status' => 1));
        
        $data = ManageGroup::model()->findAll($criteria);
        $this->smarty->assign('list', $data);
        $this->smarty->display('attach/list.tpl');
      
    }

    /**
     * 显示附件内容
     * 文档为下载，图片和视频为显示和播放
     */
    public function actionShow(){
        $qaa_id = $this->get('qaa_id');
        $attach = new QuestionAnswerAttach();
        $info = $attach->findByPk($qaa_id);
        $this->smarty->assign('info', $info);
        $this->smarty->display('attach/show.tpl');
    }
    /**
     * 添加附件
     */
    public function actionAdd(){
        $this->smarty->display('attach/add.tpl');
    }

    /**
     * 添加
     * 根据类型上传文件
     */
    public function actionDo(){
        $attach_type = $this->get('attach_type');
        $fileObj = new File();
        $bucket = isset($fileObj->attach_type[$attach_type]) ? $fileObj->attach_type[$attach_type] : 'other';
        $file = $_FILES['upfile']['tmp_name'];
        $name = $_FILES['upfile']['name'];
        $size = $_FILES['upfile']['size'];
        $content = file_get_contents($file);
        
        if ($url = $fileObj->uploadByFile($name, $file, $bucket)){
            echo '{"url":"' . $url . '","state":"SUCCESS"}';
        } else {
            echo '{"url":"' . $url . '","state":"FAILD"}';
        }
    }
    /**
     * 添加
     * 根据类型上传文件
     */
    public function actionDoanswer(){
        $attach_type = $this->get('attach_type');
        $nq_id = intval($this->request('nq_id'));
        $subject_id = intval($this->request('subject_id'));
        $fileObj = new File();
        $bucket = isset($fileObj->attach_type[$attach_type]) ? $fileObj->attach_type[$attach_type] : 'other';
        $file = $_FILES['upfile']['tmp_name'];
        $name = $_FILES['upfile']['name'];
        $size = $_FILES['upfile']['size'];
        //$content = file_get_contents($file);
        
        if ($url = $fileObj->uploadByFile($name, $file, $bucket)){
            
            $attach = new NetworkQuestionAttach();
            $attach->nq_id = $nq_id;
            $attach->subject_id = $subject_id;
            $attach->url = $url;
            $attach->create_time = time();
            $attach->update_time = time();
            $attach->save();
            
            echo '{"url":"' . $url . '","state":"SUCCESS"}';
        } else {
            echo '{"url":"' . $url . '","state":"FAILD"}';
        }
    }
    /**
     * 上传zip包
     * 问卷的附件，保函所有网点
     */
    public function actionZip(){
        $questionId = $this->post('question_id');
        $bank_id = $this->post('bank_id');
        $project_id = $this->post('project_id');
        $nqz_num = date('His');
        $upload = new Uploader();
        $config = array(
            'new_name' => $questionId.'_'.$nqz_num,
            'allow_ext' => 'zip',
            'save_path' => dirname(Yii::app()->basePath).'/assets/zip/',
            'allow_max_size' => 500000000
        );
        $upload->init($config);
        if ($upload->check()){
            $upload->up();
        }
        if ($upload->geterror()) {
            echo "{'state':'ERROR','error':'".$upload->geterror()."'}";
        } else {
                $zip = new NetworkQuestionZip();
                $zip->question_id = $questionId;
                $zip->project_id = $project_id;
                $zip->bank_id = $bank_id;
                $zip->nqz_num = $nqz_num;
                $zip->zip_name = $upload->file_name;
                $zip->is_dispose = QuestionBase::QUESTION_ATTACHMENT;
                if ($zip_res = $zip->save()){
                    echo "{'state':'SUCCESS','error':'上传成功'}";
                } else {
                    echo "{'state':'ERROR','error':'上传失败'}";
                }
        }
    }
    /**
     * 网点附件上传
     */
    public function actionNetworkZip(){
        $network_id = $this->request('network_id');
        $upload = new Uploader();
        $config = array(
            'new_name' => $network_id.'_'.time(),
            'allow_ext' => 'zip,rar',
            'save_path' => dirname(Yii::app()->basePath).'/assets/network_zip/'.$network_id,
            'allow_max_size' => 500000000
        );
        $upload->init($config);
        if ($upload->check()){
            $upload->up();
        }
        if ($upload->geterror()) {
            echo "{'state':'ERROR','error':'".$upload->geterror()."'}";
        } else {
                $attach = new NetworkAttach();
                $attach->network_id = $network_id;
                $attach->zip_name = $upload->file_name;
                $attach->create_time = time();
                $attach->url = $upload->getname();
                if ($zip_res = $attach->save()){
                    echo "{'state':'SUCCESS','error':'上传成功'}";
                } else {
                    echo "{'state':'ERROR','error':'上传失败'}";
                }
        }
    }
    /**
     * 通用网点附件，即此银行下所有网点都有的公共附件
     */
    public function actionNetcommonZip(){
        $bank_id = $this->request('bank_id');
        $upload = new Uploader();
        $config = array(
            'new_name' => $bank_id.'_'.time(),
            'allow_ext' => 'zip,rar',
            'save_path' => dirname(Yii::app()->basePath).'/assets/network_zip/bank',
            'allow_max_size' => 500000000
        );
        $upload->init($config);
        if ($upload->check()){
            $upload->up();
        }
        if ($upload->geterror()) {
            echo "{'state':'ERROR','error':'".$upload->geterror()."'}";
        } else {
            $url = $upload->getname();
            $zip_name = $upload->file_name;
            //此银行下所有网点
                $criteria = new CDbCriteria();
                $criteria->addColumnCondition(array('bank_id' => $bank_id));
            if ($list = NetWork::model()->findAll($criteria)){
                foreach ($list as $k => $v) 
                {
                    $attach = new NetworkAttach();
                    $attach->network_id = $v->network_id;
                    $attach->zip_name = $zip_name;
                    $attach->create_time = time();
                    $attach->url = $url;
                    $attach->nba_id = $bank_id;//标识是通用附件
                    $attach->save();
                }
                echo "{'state':'SUCCESS','error':'上传成功'}";
            } else {
                echo "{'state':'ERROR','error':'上传失败'}";
            }
        }
    }
    /**
     * 银行附件上传
     * 里面解压出来是网点附件
     */
    public function actionBankZip(){
        $bank_id = $this->post('bank_id');
        $nba_num = date('His');
        $upload = new Uploader();
        $config = array(
            'new_name' => $bank_id.'_'.$nba_num,
            'allow_ext' => 'zip',
            'save_path' => dirname(Yii::app()->basePath).'/assets/bank_zip/',
            'allow_max_size' => 500000000
        );
        $upload->init($config);
        if ($upload->check()){
            $upload->up();
        }
        if ($upload->geterror()) {
            echo "{'state':'ERROR','error':'".$upload->geterror()."'}";
        } else {
                $zip = new NetworkBankZip();
                $zip->bank_id = $bank_id;
                $zip->nba_num = $nba_num;
                $zip->zip_name = $upload->file_name;
                $zip->is_dispose = QuestionBase::QUESTION_ATTACHMENT;
                $zip->update_time = date('Y-m-d H:i:s');
                $zip->create_time = date('Y-m-d H:i:s');
                if ($zip_res = $zip->save()){
                    echo "{'state':'SUCCESS','error':'上传成功'}";
                } else {
                    echo "{'state':'ERROR','error':'上传失败'}";
                }
        }
    }    
    /**
     * 根据nq下载此网点问卷的附件
     */
    public function actionDownNq(){
        set_time_limit(0);
        $nq_id = $this->get('nq_id');
        $list = NetworkQuestionAttach::model()->findAll('nq_id='.intval($nq_id));
        if ($list) {
            $dir = dirname(Yii::app()->BasePath) .'/assets/nq_attach/'.$nq_id.'/';
            if (!is_dir($dir)) {
                @mkdir($dir);
            }
            $zip_file = dirname(Yii::app()->BasePath) .'/assets/nq_attach/';
            foreach ($list as $key => $val) {
                $url = $val['url'];
                $nqa_id = $val['nqa_id'];
                $info = pathinfo($url);
                $extension = $info['extension'];
                $file = $dir.$nqa_id.'.'.$extension;
                $content = file_get_contents($url);
                file_put_contents($file, $content);
            }
            //打包下载
            Yii::import('application.extensions.PHPZip', true);
            $archive  = new PHPZip();
            $archive->ZipAndDownload($zip_file);
        } else {
            echo '无附件';
        }
        
    }
	
    /**
     * 根据question_id 下载当前问卷的申诉附件
     * 太大，改成exec执行压缩
     */
    public function actionBenchmarkAttachDown(){
        $question_id = $this->get('question_id');
	$zip_file = dirname(Yii::app()->BasePath) .'/assets/benchmark_attach/'.$question_id.'/';
        if (is_readable($zip_file)) {
            $command = escapeshellcmd("zip -r -j /data/www/mystery/assets/benchmark_attach/{$question_id}.zip {$zip_file}");
            $result = exec($command,$output, $return);
            if ($result) {
                $this->_ajax(array('status' => 1,'note'=>"http://attach.hbzdcmyzb.net/{$question_id}.zip"));
            } else {
                $this->_ajax(array('status' => 0,'note'=>'执行失败'));
            }
        } else {
            $this->_ajax(array('status' => 0,'note'=>'没有附件'));
        }
        
    }
	
	/**
	 * 根据project_id，下载项目下的报备附件
	 */
	public function actionDownProjectReport(){
        set_time_limit(0);
		$project_id = (int)$this->get('project_id');
		if (!$project_id) {
            $this->jump('请先选择要导出的项目');
        }
        $netreport = new NetworkReport();
        $criteria = new CDbCriteria();
        if ($project_id) 
        {
            $criteria->addColumnCondition(array('project_id' => $project_id));
        }
        $criteria->addCondition('status!=0');
	$list = $netreport->findAll($criteria);	
        if ($list) {
            # 获取attach
            $reportIds = array();
            foreach ($list as $value) {
                $reportIds[] = $value['nr_id'];
            }
            $reportAttach = NetworkReportAttach::model()->findAll('nr_id in(' . join(',', $reportIds) . ')');

            if ($reportAttach) {
                foreach ($reportAttach as $key => $val) {
                    $filename = $val['file_name'];
                    $network_id = $val['network_id'];
                    $project_id = $val['project_id'];
                    $file = dirname(Yii::app()->BasePath) .'/assets/report_attach/'.$network_id.'/'.$filename;
                    $command = escapeshellcmd("zip -m -j /data/www/mystery/assets/benchmark_attach/report_{$project_id}.zip {$file}");
                    $result = exec($command,$output, $return);
                }  
                if (file_exists("/data/www/mystery/assets/benchmark_attach/report_{$project_id}.zip")) {
                    $this->jump('确定下载', "http://attach.hbzdcmyzb.net/report_{$project_id}.zip");
                } else {
                    $this->jump('当前项目无报备附件信息');
                }
            } else {
                $this->jump('当前项目无报备附件信息');
            }
        } else {
            $this->jump('当前项目无报备附件信息');
        }
    }
	
	
    /**
     * 删除附件
     */
    public function actiondel(){
       $qaa_id = $this->get('qaa_id');
       $attach = new QuestionAnswerAttach();
        if ($attach->updateByPk($qaa_id, array('status' => 0))){
            $this->_ajax(array('status' => 1,'note' => '成功'));
        } else {
            $this->_ajax(array('status' => 0,'note' => '失败'));
        }
    }
    public function beforeAction($action) {
        return true;
    }
	
	
	/**
	 * 系统内调用删除目录和目录下的所有文件
	 * @param type $dir
	 * @return boolean
	 */
	private function actionDeldir($dir) {
		if (!$dir) {
			return false;
		}
		//先删除目录下的文件：
		$dh = opendir($dir);
		while ($file = readdir($dh)) {
			if ($file != "." && $file != "..") {
				$fullpath = $dir . "/" . $file;
				if (!is_dir($fullpath)) {
					unlink($fullpath);
				} else {
					$this->actionDeldir($fullpath);
				}
			}
		}

		closedir($dh);
		//删除当前文件夹：
		if (rmdir($dir)) {
			return true;
		} else {
			return false;
		}
	}

}

